/*
 * @Author: zhangyun
 * @Date: 2021-04-26 15:20:31
 * @LastEditors: zhangyun
 * @LastEditTime: 2021-04-26 16:50:43
 * @Desc:
 */
const express = require('express')
const router = express.Router()
const _ = require('lodash')
const userModel = require('../model/userModel')
const message = require('../utils/message')
const bcryptjs = require('bcryptjs')
const jwt = require('jsonwebtoken')
const SECRET = 'ewgfvwergvwsgw5454gsrgvsvsd'

router.get('/', async (req, res) => {
  const { user, pwd } = req.query
  console.log('=====', user, pwd)
  if (_.isEmpty(user) || _.isEmpty(pwd)) return res.status(400).send(message(400, '用户名或密码不能为空'))
  const result = await userModel.findOne({ user: user })
  if (_.isEmpty(result)) return res.status(422).send(message(422, '用户不存在'))
  const isPasswordValid = bcryptjs.compareSync(pwd, result.pwd)
  if (!isPasswordValid) return res.status(422).send(message(422, '密码无效'))
  // token
  const token = jwt.sign({ id: String(result._id) }, SECRET)
  res.status(200).send(
    message(200, '登陆成功', {
      result,
      token,
    })
  )
})

module.exports = router
